package com.hm.service.impl.login;

import com.google.zxing.BarcodeFormat;
import com.google.zxing.client.j2se.MatrixToImageWriter;
import com.google.zxing.common.BitMatrix;
import com.google.zxing.qrcode.QRCodeWriter;
import com.hm.service.framework.base.BaseServiceImpl;
import com.hm.service.service.main.LoginQRCodeService;
import org.springframework.beans.factory.annotation.Qualifier;
import org.springframework.stereotype.Service;

import javax.imageio.ImageIO;
import java.awt.image.BufferedImage;
import java.io.ByteArrayOutputStream;
import java.util.Base64;


@Service
public class LoginQRCodeServiceImpl extends BaseServiceImpl implements LoginQRCodeService {
    private static final int QR_CODE_SIZE = 300; // 二维码的宽度和高度


    @Qualifier("QRCodeWriter")
    private final QRCodeWriter qrCodeWriter;

    public LoginQRCodeServiceImpl(QRCodeWriter qrCodeWriter) {
        this.qrCodeWriter = qrCodeWriter;
    }

    @Override
    public String generateQRCode() {
        try {
            //待编码的文本
            String textToEncode = "http://172.26.2.18:3000/WitCityManage?QRcodeId=1111sdfasdfsdf123123SDA";
            //QRCodeWriter qrCodeWriter = new QRCodeWriter();
            BitMatrix bitMatrix = qrCodeWriter.encode(textToEncode, BarcodeFormat.QR_CODE, QR_CODE_SIZE, QR_CODE_SIZE);
            BufferedImage bufferedImage = MatrixToImageWriter.toBufferedImage(bitMatrix);
            ByteArrayOutputStream byteArrayOutputStream = new ByteArrayOutputStream();
            //将图片写入输出流
            ImageIO.write(bufferedImage, "png", byteArrayOutputStream);
            byte[] byteArray = byteArrayOutputStream.toByteArray();
            //进行base64编码
            return Base64.getEncoder().encodeToString(byteArray);
        } catch (Exception e) {
            throw new RuntimeException(e);
        }
    }
}
